using System.Collections;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float _bulletspeed;
    public int _timeToLive;
    private Rigidbody2D _rigidbody2D;
    private MainFrame _owner;

    private void Awake()
    {
        _rigidbody2D = GetComponent<Rigidbody2D>();
    }

    public void InitializeBullet(Vector2 cruiserSpeed, GameObject weapon, MainFrame owner)
    {
        transform.position = weapon.transform.position;
        transform.rotation = weapon.transform.rotation;
        _rigidbody2D.velocity = new Vector2(transform.up.x, transform.up.y) * _bulletspeed + cruiserSpeed;
        _owner = owner;
        StartCoroutine(LifeCountdown());
    }

    private IEnumerator LifeCountdown()
    {
        int _timer = _timeToLive;
        while (_timer > 0)
        {
            _timer--;
            yield return null;
        }
        gameObject.SetActive(false);
    }

    //private void OnCollisionEnter2D(Collision2D collision)//todo
    //{
    //    Debug.Log("collision");
    //    if (collision.gameObject.name == "Cruiser_1")
    //    {
    //        Debug.Log("Hit");
    //        return;
    //    }
    //}

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.name != _owner.name && collision.gameObject.tag == ObjectTag.Mainframe)
        {
            //bullet with a buff "SlowDown"
            AssetsManager.AssetsManagerInstance.DeserializeBuff(BuffName.SlowDown).RegisterBuff(_owner.GetComponent<BuffManager>(), collision.gameObject.GetComponent<BuffManager>());
            gameObject.SetActive(false);
            return;
        }
    }
}
